<?php
namespace app\crawler\controller;

use app\model\CollectSet;
use app\model\Items;

class DtkController extends BaseController{

    protected $item_model;
    protected $item_cate; //商品分类

    protected function _initialize(){
        parent::_initialize();
        $this->item_model = new Items();
        $this->item_cate = CollectSet::where('type','dtk')->column('org_cate,cate');
    }
    /**
     * [collect description]
     * 采集
     * @return [type] [description]
     */
    public function collect(){

        $page = $this->request->get('page');
        $totalPage = $page + 10;

        echo 'page='.$page.';total='.$totalPage;

        while ( $page < $totalPage) {
            $data = array();
            $urls = array();
            for ($i=$page; $i <= $page+4; $i++) {
                $urls[] = "http://api.dataoke.com/index.php?r=Port/index&type=total&appkey=cy914zj5wg&v=2&page=".$i;
            }


            $p = 5;//每次执行多少条
            $ring = ceil(count($urls) / $p);
            for($n = 0; $n < $ring; $n++){
                $temp_url = array();
                $star = $n * $p;
                $end = ($n+1) * $p;
                for($ii = $star; $ii < $end; $ii++)
                {
                    if (isset($urls[$ii]))
                    {
                        $temp_url[] = $urls[$ii];
                    }

                }
            }

            $mh = curl_multi_init();
            foreach ($temp_url as $i => $url) {
                $conn[$i] = curl_init($url);
                curl_setopt($conn[$i], CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
                curl_setopt($conn[$i], CURLOPT_HEADER, 0);
                curl_setopt($conn[$i], CURLOPT_SSL_VERIFYPEER, FALSE);
                curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, TRUE);
                curl_setopt($conn[$i], CURLOPT_TIMEOUT, 60);
                curl_setopt($conn[$i], CURLOPT_URL, $url);
                curl_multi_add_handle($mh,$conn[$i]);
            }

            do{
                $mrc = curl_multi_exec($mh, $active);
            } while ($mrc == CURLM_CALL_MULTI_PERFORM);

            while ($active and $mrc == CURLM_OK){
                if (curl_multi_select($mh) != -1){
                    do {
                        $mrc = curl_multi_exec($mh, $active);
                    } while ($mrc == CURLM_CALL_MULTI_PERFORM);
                }
            }

            $active = null;

            foreach ($temp_url as $i => $url) {

                $output = curl_multi_getcontent($conn[$i]); // 获得爬取的代码字符串
                $result = json_decode($output,true);
                $data = array_merge($data,$result['result']);

            }

            //var_dump($data);

            foreach ($temp_url as $i => $url) {
                curl_multi_remove_handle($mh, $conn[$i]);
                curl_close($conn[$i]);
            }
            curl_multi_close($mh);

            $this->dtkcollect($data);
            $page += 4;

        }
        echo '采集完成前'.$page.'页</br>';
    }

    public function checkExpire(){
        $this->item_model
            ->where(array('coupon_end_time'=>array('lt',time())))
            ->delete();
        echo '过期检测完成';
    }

    public function dtkcollect($map = array()){

        $data = array();
        $time = time();
        for ($i=0; $i < count($map); $i++) {
            if(Items::get(['item_id' => $map[$i]['GoodsID']])){
                continue;
            }
            if($map[$i]['Commission_jihua']>$map[$i]['Commission_queqiao']){
                if(empty($map[$i]['Jihua_link'])){
                    $tktype = 1;
                }
                else{
                    $tktype = 3;
                }
            }
            else{
                $tktype = 2;
            }

            $cid = $map[$i]['Cid'];
            if(empty($this->item_cate[$cid])){
                continue;
            }

            $data[] = array(
                'title' => $map[$i]['D_title'],
                'item_id' => $map[$i]['GoodsID'],
                'cate_id' => $this->item_cate[$cid],
                'introduce' => $map[$i]['Introduce'],
                'pic_url' => $map[$i]['Pic'],
                'item_url' => 'https://item.taobao.com/item.htm?id='.$map[$i]['GoodsID'],
                'org_price' => $map[$i]['Org_Price'],
                'price' => $map[$i]['Price'],
                'sales' => $map[$i]['Sales_num'],
                'coupon_id' => $map[$i]['Quan_id'],
                'coupon_money' => $map[$i]['Quan_price'],
                'coupon_url' => $map[$i]['Quan_link'],
                'coupon_start_time' => $time,
                'coupon_end_time' => strtotime($map[$i]['Quan_time']),
                'shop_type' => $map[$i]['IsTmall'],
                'seller_id' => $map[$i]['SellerID'],
                'tk_rate' => $map[$i]['Commission_jihua']>$map[$i]['Commission_queqiao'] ? $map[$i]['Commission_jihua']:$map[$i]['Commission_queqiao'],
                'tk_type' => $tktype,
                'status' => '2',
            );
        }
        $this->item_model->saveAll($data);

        return true;
    }

}